﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.Data;
using OF.Common;
using System.Configuration;
namespace OF.BLL.Order
{
    /// <summary>
    ///订单接口实现
    /// </summary>
    public class Order : DAL.Orders
    {
        static DAL.Orders dal_order = new DAL.Orders();
        static DAL.OrderDetail dal_odetail = new DAL.OrderDetail();
        static DAL.Seller dal_seller = new DAL.Seller();
        static DAL.Dish dal_dish = new DAL.Dish();

        #region 订单表属性赋值
        private Model.Orders BindOrderInfo(Model.Orders order, string sellerid, string buyerid, string scheduledtime, string phone, string sendaddress, string population, string remark, string type,string state)
        {
            order.sellerid = Convert.ToInt32(sellerid);
            order.buyerid = Convert.ToInt32(buyerid);
            order.phone = phone;
            order.scheduledtime = scheduledtime.Replace('+', '-');
            order.remark = remark;
            order.addtime = DateTime.Now;
            if (type == "waimai") //外卖
            {
                order.ordertype = 1;
                order.sendaddress = sendaddress;
            }
            else
            {  //点餐
                order.ordertype = 2;
                order.population = Convert.ToInt32(population);
            }
            //订单状态
            if (state.ToUpper() == "INIT")
                order.state = Convert.ToInt32(OF.Common.Enmus.ORDER_STATE.INIT);
            else if (state.ToUpper() == "WAIT_SUBMIT")
                order.state = Convert.ToInt32(OF.Common.Enmus.ORDER_STATE.WAIT_SUBMIT);
            return order;
        }
        #endregion

        #region 订餐提交接口 order.add
        public string doAddOrder(string sellerid, string buyerid, string dishs, string scheduledtime, string phone,
             string sendaddress, string population, string remark, string type, string state)
        {
            string result = Enmus.RETURN.FAIL.ToString();
            try
            {
                Model.Orders order = new Model.Orders();
                //流水号
                order.ordersn = CreateOrderNumber();//DateTime.Now.Ticks.ToString();
                //订单实体赋值
                order = BindOrderInfo(order, sellerid, buyerid, scheduledtime, phone, sendaddress, population, remark, type,state);
               
                //查询送餐价格
                Model.Seller model_seller = dal_seller.GetModel(Convert.ToInt32(order.sellerid));
                //商家信息不存在，则返回失败
                if (model_seller == null)
                    return result;
                order.sendprice = model_seller.tip == null ? 0 : model_seller.tip;
                //解析订单详细,累加订单金额 
                List<Model.OrderDetail> details = ParseDishs(dishs, order);
                if (details == null)
                    return result;
                //订单表点菜总价
                order.dishprice = details.Sum(c => c.allprice);
                //订单总额
                order.allprice = order.dishprice + order.sendprice;
                //插入订单
                int newid = Add(order);
                if (newid > 0)
                {
                    foreach (Model.OrderDetail detail in details)
                    {
                        detail.orderid = newid;
                        detail.buyerid = order.buyerid;
                        // 插入订单详情
                        if (dal_odetail.Add(detail) <= 0)
                        {
                            return result;
                        }
                    }
                    //插入明细成功
                    result = Enmus.RETURN.SUC.ToString();
                }
            }
            catch (Exception e)
            {
                result = Enmus.RETURN.ERROR.ToString();
                Common.LogHelper.WriteLog(e.ToString(), "doAddOrder");
            }
            return result;
        }
        public string CreateOrderNumber()
        {
            string ordersn = DateTime.Now.ToString("yyMMddHHmmss")+ Next(1000, 1).ToString();
            //判断流水号是否存在
            var ds = dal_order.GetList(" ordersn='" + ordersn + "'") ;
            if (ds!=null && ds.Tables[0]!=null && ds.Tables[0].Rows.Count>0)
            {
               return CreateOrderNumber();
            }
            else {
                return ordersn ;
            }
           
        }
        private static int Next(int numSeeds, int length)
        {
            byte[] buffer = new byte[length];
            System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
            Gen.GetBytes(buffer);
            uint randomResult = 0x0;//这里用uint作为生成的随机数  
            for (int i = 0; i < length; i++)
            {
                randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
            }
            return (int)(randomResult % numSeeds);
        }
        #endregion

        #region 订单修改接口 order.update.info
        public string doUpdateOrder(string orderid, string sellerid, string dishs, string scheduledtime,
             string sendaddress, string population, string remark, string type)
        {
            string result = Enmus.RETURN.FAIL.ToString();
            try
            {
                //根据orderid查询订单信息
                Model.Orders order = dal_order.GetModel(Convert.ToInt32(orderid));
                if (order == null)
                    return result;
                //判断订单状态，不是待提交返回
                if (order.state != Convert.ToInt32(Enmus.ORDER_STATE.WAIT_SUBMIT))
                    return result= Enmus.RETURN.NOT_USE.ToString();
                //订单实体赋值
                order = BindOrderInfo(order, sellerid, order.buyerid.ToString(), scheduledtime, order.phone, sendaddress, population, remark, type, Enmus.ORDER_STATE.WAIT_SUBMIT.ToString());
               
                //查询送餐价格
                Model.Seller model_seller = dal_seller.GetModel(Convert.ToInt32(order.sellerid));
                //商家信息不存在，则返回失败
                if (model_seller == null)
                    return result;
                order.sendprice = model_seller.tip == null ? 0 : model_seller.tip;
                //解析订单详细,累加订单金额 
                List<Model.OrderDetail> details = ParseDishs(dishs, order);
                if (details == null)
                    return result;
                //订单表点菜总价
                order.dishprice = details.Sum(c=>c.allprice);
                //订单总额
                order.allprice = order.dishprice + order.sendprice;
                //更新订单
                if (Update(order))
                {
                    //删除订单明细
                    if(!dal_odetail.DeleteByOrderid(order.id))
                        return result;
                    foreach (Model.OrderDetail detail in details)
                    {
                        detail.orderid = order.id;
                        detail.buyerid = order.buyerid;
                        // 插入订单详情
                        if (dal_odetail.Add(detail) <= 0)
                        {
                            return result;
                        }
                    }
                    //插入明细成功
                    result = Enmus.RETURN.SUC.ToString();
                }
            }
            catch (Exception e)
            {
                result = Enmus.RETURN.ERROR.ToString();
                Common.LogHelper.WriteLog(e.ToString(), "doUpdateOrder");
            }
            return result;
        }
        #endregion

        #region 解析订单详情
        private List<Model.OrderDetail> ParseDishs(string dishs,Model.Orders order)
        {
            //解析json并拼接id字符串
            List<Model.OrderDetail> list = Json.Deserialize<List<Model.OrderDetail>>(dishs);
            StringBuilder detailIds = new StringBuilder();
            foreach (Model.OrderDetail detail in list)
            {
                detailIds.Append(detail.dishid + ",");
            }
            //查询菜品信息
            var dishDs = dal_dish.GetList(" id in(" + detailIds.Remove(detailIds.Length - 1, 1) + ")");
            if (dishDs == null || dishDs.Tables[0] == null || dishDs.Tables[0].Rows.Count == 0)
                return null;

            int count = dishDs.Tables[0].Rows.Count;
            List<Model.OrderDetail> newList = new List<Model.OrderDetail>();
            var dishTable= dishDs.Tables[0];
            for (int i = 0; i < count; i++)
            {
                var dishRow = dishTable.Rows[i];
                Model.OrderDetail detail = new Model.OrderDetail();
                detail.dishid = Convert.ToInt32(dishRow["id"].ToString());
                //从json集合里取出数量
                detail.count = list.Where(c => c.dishid == detail.dishid).Select(c => c.count).ToList()[0];
                detail.price = Convert.ToDecimal(dishRow["price"].ToString());
                //菜品总价
                detail.allprice = detail.price * detail.count;
                detail.dishname = dishRow["dishname"].ToString();
                newList.Add(detail);
            }
            return newList;
        }
        #endregion

        #region 根据用户查询订单列表 order.orderlist.get
        public string doGetOrderList(string buyerid, string pageid, string state)
        {
            string result;
            string json = "{\"BuyerOrderList\":[";
            try
            {
                if (state.ToUpper() == "WAIT_SUBMIT") state = " and state=6";
                else if (state.ToUpper() == "INIT") state = " and state in(0,1,2)";
                else if (state.ToUpper() == "COMPLETE") state = " and state=3";
                else if (state.ToUpper() == "NOT_COMPLETE") state = " and state in(4,5)";

                string where = "buyerid=" + buyerid + "" + state + "";
                string order = " addtime desc";
                int pageindex = Common.Utils.StrToInt(pageid, 1);
                int pagesize = 10;

                DataSet ds = GetPageList(where, order, pageindex, pagesize);
                DataTable dt = ds.Tables[0];
                if (ds != null && ds.Tables[0] != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        json += "{\"id\":\"" + dt.Rows[i]["id"] + "\",\"ordersn\":\"" + dt.Rows[i]["ordersn"] + "\",\"allprice\":\"" + dt.Rows[i]["allprice"] + "\",\"buyerid\":\"" + dt.Rows[i]["buyerid"] + "\",\"phone\":\"" + dt.Rows[i]["phone"] + "\",\"addtime\":\"" + dt.Rows[i]["addtime"] + "\",\"population\":\"" + dt.Rows[i]["population"] + "\",\"remark\":\"" + dt.Rows[i]["remark"] + "\",\"state\":\"" + dt.Rows[i]["state"] + "\",\"ordertype\":\"" + dt.Rows[i]["ordertype"] + "\",\"sendaddress\":\"" + dt.Rows[i]["sendaddress"] + "\",\"sendprice\":\"" + dt.Rows[i]["sendprice"] + "\",\"dishprice\":\"" + dt.Rows[i]["dishprice"] + "\",\"sellerid\":\"" + dt.Rows[i]["sellerid"] + "\",";
                        string shopname = dal_seller.GetModel(Common.TypeConverter.StrToInt(dt.Rows[i]["sellerid"].ToString())).shopname;
                        json += "\"shopname\":\"" + shopname + "\",";
                        DataSet ds2 = dal_odetail.GetList("orderid='" + dt.Rows[i]["id"] + "'");
                        DataTable dt2 = ds2.Tables[0];
                        string detail = "[";
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            detail += "{\"dishid\":\"" + dt2.Rows[j]["dishid"] + "\",\"dishname\":\"" + dt2.Rows[j]["dishname"] + "\",\"count\":\"" + dt2.Rows[j]["count"] + "\",\"price\":\"" + dt2.Rows[j]["price"] + "\",\"allprice\":\"" + dt2.Rows[j]["allprice"] + "\"},";
                        }
                        if (detail.Length > 1) detail = detail.Substring(0, detail.Length - 1);
                        detail += "]";
                        json += "\"orderdetail\":" + detail + "},";
                    }
                    json = json.Substring(0, json.Length - 1);
                }
                json += "]}";
                result = json;
            }
            catch (Exception e)
            {
                result = Enmus.RETURN.ERROR.ToString();
                Common.LogHelper.WriteLog(e.ToString(), "doGetOrderList");
            }
            return result;
        }
        #endregion

        #region 修改订单 order.update
        public string UpdateOrder(string orderid, string modify, string usertype)
        {
            string result = Enmus.RETURN.FAIL.ToString();
            try
            {
                int state = 0;
                modify = modify.ToLower();
                //验证订单状态
                if (modify == "init")
                    state = Convert.ToInt32(Enmus.ORDER_STATE.INIT);
                else if (modify == "cancel")
                    state = Convert.ToInt32(Enmus.ORDER_STATE.CANCEL);
                else if (modify == "invalid")
                    state = Convert.ToInt32(Enmus.ORDER_STATE.INVALID);
                else if (modify == "complete")
                    state = Convert.ToInt32(Enmus.ORDER_STATE.COMPLETE);
                else if (modify == "confirm_suc")
                    state = Convert.ToInt32(Enmus.ORDER_STATE.CONFIRM_SUC);
                else if (modify == "confirm_fail")
                    state = Convert.ToInt32(Enmus.ORDER_STATE.CONFIRM_Fail);

                //查询旧状态
                Model.Orders model = GetModel(Convert.ToInt32(orderid));
                if (model != null && Update(orderid, state))
                {
                    int uid = Convert.ToInt32(model.buyerid);
                    if (usertype.Equals("seller")) uid = Convert.ToInt32(model.sellerid);
                    //插入订单日志
                    if (AddOrderLog(Convert.ToInt32(model.state), state, Convert.ToInt32(orderid), 1, uid))
                        result = Enmus.RETURN.SUC.ToString();
                }
            }
            catch (Exception e)
            {
                result = Enmus.RETURN.ERROR.ToString();
                Common.LogHelper.WriteLog(e.ToString(), "UpdateOrder");
            }
            return result;
        }
        #endregion

        #region 根据卖家id查询订单列表 order.sellerorder.get
        public string doGetOrderList(string userid, string usertype, string ordertype, string state, string operate, string id)
        {
            string result = Enmus.RETURN.NULL.ToString();
            string json = "{\"OrderList\":[";
            try
            {
                if (string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(usertype) || string.IsNullOrEmpty(ordertype) || string.IsNullOrEmpty(state))
                    return Enmus.RETURN.ERROR.ToString();

                string _user = "buyer";
                if (usertype == "buyer") _user = " buyerid=" + userid;
                else if (usertype == "seller") _user = " sellerid=" + userid;

                string _ordertype = "waimai";
                if (ordertype == "waimai") _ordertype = " and ordertype=1";
                if (ordertype == "diancan") _ordertype = " and ordertype=2";

                string _state = "WAIT_HANDLE";
                state=state.ToUpper();
                if (state == "WAIT_SUBMIT") _state = " and state=6";               //待提交
                else if (state == "INIT") _state = " and state in(0,1,2)";         //已下单
                else if (state == "COMPLETE") _state = " and state=3";             //已完成
                else if (state == "NOT_COMPLETE") _state = " and state in(4,5)";   //未完成
                else if (state == "WAIT_HANDLE") _state = " and state=0";          //待处理
                else if (state == "HANDLED") _state = " and state in(1,2,3)";      //已完成

                string sql = _user + _ordertype + _state;

                DataSet ds = null;
                if (id.Equals("0"))
                    ds = GetOrderFirst(sql);

                else if (operate == "down")
                    ds = GetOrderDown(id, sql);
                else if (operate == "up")
                    ds = GetOrderUp(id, sql);

                if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        json += "{\"id\":\"" + dt.Rows[i]["id"] + "\",\"ordersn\":\"" + dt.Rows[i]["ordersn"] + "\",\"allprice\":\"" + dt.Rows[i]["allprice"] + "\",\"buyerid\":\"" + dt.Rows[i]["buyerid"] + "\",\"phone\":\"" + dt.Rows[i]["phone"] + "\",\"addtime\":\"" + dt.Rows[i]["addtime"] + "\",\"scheduledtime\":\"" + dt.Rows[i]["scheduledtime"] + "\",\"population\":\"" + dt.Rows[i]["population"] + "\",\"remark\":\"" + dt.Rows[i]["remark"] + "\",\"state\":\"" + dt.Rows[i]["state"] + "\",\"ordertype\":\"" + dt.Rows[i]["ordertype"] + "\",\"sendaddress\":\"" + dt.Rows[i]["sendaddress"] + "\",\"sendprice\":\"" + dt.Rows[i]["sendprice"] + "\",\"dishprice\":\"" + dt.Rows[i]["dishprice"] + "\",\"sellerid\":\"" + dt.Rows[i]["sellerid"] + "\",";
                        string shopname = dal_seller.GetModel(Common.TypeConverter.StrToInt(dt.Rows[i]["sellerid"].ToString())).shopname;
                        json += "\"shopname\":\"" + shopname + "\",";
                        DataSet ds2 = dal_odetail.GetList("orderid='" + dt.Rows[i]["id"] + "'");
                        DataTable dt2 = ds2.Tables[0];
                        string detail = "[";
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            detail += "{\"dishid\":\"" + dt2.Rows[j]["dishid"] + "\",\"dishname\":\"" + dt2.Rows[j]["dishname"] + "\",\"count\":\"" + dt2.Rows[j]["count"] + "\",\"price\":\"" + dt2.Rows[j]["price"] + "\",\"allprice\":\"" + dt2.Rows[j]["allprice"] + "\"},";
                        }
                        if (detail.Length > 1) detail = detail.Substring(0, detail.Length - 1);
                        detail += "]";
                        json += "\"orderdetail\":" + detail + "},";
                    }
                    json = json.Substring(0, json.Length - 1);
                }
                json += "]}";
                result = json;
            }
            catch (Exception e)
            {
                result = Enmus.RETURN.ERROR.ToString();
                Common.LogHelper.WriteLog(e.ToString(), "doGetSellerOrderList");
            }
            return result;
        }
        #endregion

        #region 根据订单号查询详细信息 order.sellerorderinfo.get
        public string doGetSellerOrderInfo(string orderid)
        {
            string result = Enmus.RETURN.NULL.ToString();
            try
            {
                DataSet ds = dal_odetail.GetOrderDishList(orderid);
                if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    return Json.DataTableToJson("SellerOrderDetail", ds.Tables[0]);
                }
            }
            catch (Exception e)
            {
                result = Enmus.RETURN.ERROR.ToString();
                Common.LogHelper.WriteLog(e.ToString(), "doGetSellerOrderInfo");
            }
            return result;
        }
        public DataSet GetOrderDetailsById(int orderid)
        {
            return dal_odetail.GetList("orderid=" + orderid);
        }
        #endregion

        #region 添加订单评论 order.comment.add

        public string addOrderComment(string buyerid, string orderid, string eat_score, string serve_score, string details)
        {
            string result = Enmus.RETURN.NULL.ToString();
            DAL.Comment dal_comment = new DAL.Comment();

            int count= dal_order.GetRecordCount("buyerid=" + buyerid + " and id=" + orderid);
            if (count == 0) return result = "NOT ALLOW"; //该用户无该订单

            int countComment= dal_comment.GetRecordCount("buyerid=" + buyerid + " and orderid=" + orderid);
            if (countComment > 0) return result = "HAVE DO";//已经评论过

            Model.Comment model_comment = new Model.Comment();
            model_comment.addtime = DateTime.Now;
            model_comment.buyerid = Common.Utils.StrToInt(buyerid,0);
            model_comment.orderid = Common.Utils.StrToInt(orderid, 0);
            model_comment.eat_score =Convert.ToDecimal(Common.Utils.ToFloat(eat_score, 5));
            model_comment.serve_score = Convert.ToDecimal(Common.Utils.ToFloat(serve_score, 5));
            model_comment.details = details;

            int r= dal_comment.Add(model_comment);
            if (r > 0)
            {
                UpdateOrder(orderid, "complete", "buyer");//更新订单状态
                result = Enmus.RETURN.SUC.ToString();
            }
            else
            {
                result = Enmus.RETURN.FAIL.ToString();
            }
            return result;
        }

        #endregion

        #region 插入日志
        /// <summary>
        /// 插入日志
        /// </summary>
        /// <param name="state"></param>
        /// <param name="orderid"></param>
        /// <param name="type"> 1 买家 2 卖家 3 系统</param>
        /// <param name="uid"> type=1 是buyerid type=2 是sellerid</param>
        /// <returns></returns>
        public bool AddOrderLog(int oldstate, int state, int orderid, int type, int uid)
        {
            DAL.OrderLog dal_log = new DAL.OrderLog();
            Model.OrderLog model = new Model.OrderLog();
            model.addtime = DateTime.Now;
            model.before_state = oldstate;
            model.after_state = state;
            model.orderid = orderid;
            model.type = type;
            model.uid = uid;
            return dal_log.Add(model) > 0 ? true : false;
        }
        #endregion
    }
}
